<template>
    <div>
      <!-- Breadcrumbs removed per spec -->
  
      <!-- Top actions -->
      <div class="d-flex align-center justify-space-between mb-3">
        <div class="text-h6 font-weight-bold page-title">Generator Unit</div>
        <div class="d-flex align-center">
          <v-text-field
            v-model="search"
            dense
            hide-details
            outlined
            prepend-inner-icon="mdi-magnify"
            label="Search"
            class="mr-3"
            style="max-width: 350px"
          />
          <v-btn class="mr-2" outlined>Export</v-btn>
          <v-btn color="primary" dark>+ Add</v-btn>
        </div>
      </div>
  
      <!-- Table -->
      <div class="table-wrapper">
        <v-data-table
          :headers="headers"
          :items="displayRows"
          :search="search"
          class="elevation-1"
          dense
        >
  
          <template v-slot:item.no="{ index }">
            {{ index + 1 }}
          </template>
  
          <!-- Valid flag -->
          <template v-slot:item.valid="{ item }">
            <StatusChip :status="item.valid" true-text="Valid" false-text="Invalid" />
          </template>
  
          <!-- Allow start/stop within period -->
          <template v-slot:item.allowStartStopWithinPeriod="{ item }">
            <StatusChip :status="item.allowStartStopWithinPeriod" true-text="Yes" false-text="No" />
          </template>
        </v-data-table>
      </div>

  <!-- Floating Assistant (bottom-right) -->
  <div class="ai-assistant">
    <!-- Docked (collapsed) bar -->
    <div v-if="!assistantExpanded" class="ai-dock elevation-6">
      <div class="dock-left">AI Assistant</div>
      <div class="dock-actions">
        <v-btn small icon @click="assistantExpanded=true">
          <v-icon>mdi-plus</v-icon>
        </v-btn>
      </div>
    </div>

    <!-- Expanded panel -->
    <v-card v-else class="ai-panel elevation-10">
      <div class="ai-header d-flex align-center justify-space-between">
        <div class="font-weight-bold">AI Assistant</div>
        <div>
          <v-btn small depressed class="mr-2" @click="assistantMode='text'">Text</v-btn>
          <v-btn small icon :color="isRecording ? 'red' : 'success'" class="mr-2" @click="toggleRecording">
            <v-icon>{{ isRecording ? 'mdi-microphone' : 'mdi-microphone-outline' }}</v-icon>
          </v-btn>
          <v-btn small icon @click="assistantExpanded=false"><v-icon>mdi-minus</v-icon></v-btn>
        </div>
      </div>
      <v-divider></v-divider>
      <div class="ai-body">
        <div class="ai-greeting">
          {{ assistantMode==='voice' && lastTranscript ? lastTranscript : 'Hello! I can help you manage generator data. Ask me anything about the form or data entry.' }}
        </div>

        <div v-if="assistantMode==='voice'" class="ai-voice text-center">
          <v-btn :color="isRecording ? 'red' : 'success'" class="mic-btn" fab large @click="toggleRecording">
            <v-icon large>mdi-microphone</v-icon>
          </v-btn>
          <div class="mt-2 grey--text text--darken-1">{{ isRecording ? 'Recording...' : 'Press to start recording' }}</div>
        </div>

        <div v-else class="ai-text">
          <v-text-field v-model="assistantText" outlined hide-details placeholder="Type your question..."/>
          <div class="mt-2 d-flex justify-end">
            <v-btn color="primary" @click="sendAssistantText">Send</v-btn>
          </div>
        </div>
      </div>
    </v-card>
  </div>
    </div>
  </template>
  
  <script>
import SpeechRecognizer from '@/api/simpson-stt.js'
  /** Reusable status chip component */
  const StatusChip = {
    props: {
      status: Boolean,
      trueText: { type: String, default: 'Yes' },
      falseText: { type: String, default: 'No' }
    },
    template: `
      <v-chip
        small
        :color="status ? 'green lighten-4' : 'red lighten-4'"
        :text-color="status ? 'green darken-2' : 'red darken-2'"
      >
        {{ status ? trueText : falseText }}
      </v-chip>
    `
  }
  
  export default {
    name: 'Simulation',
    components: { StatusChip },
  
    data() {
      return {
        search: '',
        // Assistant state
        assistantExpanded: false,
        assistantMode: 'text', // 'text' | 'voice'
        isRecording: false,
        isConnected: false,
        assistantText: '',
        lastTranscript: '',
        // STT config
        wsUrl: process.env.VUE_APP_STT_WS || 'ws://localhost:8080/ws',
        sessionId: 'session123',
        recognizer: null,
        // Breadcrumbs removed per spec
        headers: this.getTableHeaders(),
        rows: this.generateMockRows()
      }
    },
  
    computed: {
      displayRows() {
        const toFixed2 = (v) => {
          if (v === null || v === undefined) return v
          if (typeof v !== 'number') return v
          return Number.isFinite(v) ? Number(v.toFixed(2)) : v
        }
        return this.rows.map(r => ({
          ...r,
          maxTechOutputRate: toFixed2(r.maxTechOutputRate),
          minTechOutputRate: toFixed2(r.minTechOutputRate),
          plantPowerConsumptionRate: toFixed2(r.plantPowerConsumptionRate),
          maxHourlyRampRate: toFixed2(r.maxHourlyRampRate),
          firstSegmentStartOutputRate: toFixed2(r.firstSegmentStartOutputRate),
          firstSegmentEndOutputRate: toFixed2(r.firstSegmentEndOutputRate),
          secondSegmentEndOutputRate: toFixed2(r.secondSegmentEndOutputRate),
          thirdSegmentEndOutputRate: toFixed2(r.thirdSegmentEndOutputRate),
          fourthSegmentEndOutputRate: toFixed2(r.fourthSegmentEndOutputRate),
          fifthSegmentEndOutputRate: toFixed2(r.fifthSegmentEndOutputRate)
        }))
      }
    },
  
    methods: {
      async toggleRecording() {
        this.assistantMode = 'voice'
        if (this.isRecording) {
          this.stopRecognition()
        } else {
          await this.startRecognition()
        }
      },
      async startRecognition() {
        try {
          this.lastTranscript = ''
          this.recognizer = new SpeechRecognizer()
          const token = window.localStorage.getItem('token')
          await this.recognizer.recognize(
            this.wsUrl,
            token,
            this.handleRecognitionResult
          )
          this.isConnected = this.recognizer.isConnected
          this.isRecording = this.recognizer.isRecording
        } catch (error) {
          // eslint-disable-next-line no-console
          console.error('Start STT failed:', error)
          this.isConnected = false
          this.isRecording = false
        }
      },
      stopRecognition() {
        try {
          if (this.recognizer) this.recognizer.stop()
        } catch (error) {
          // eslint-disable-next-line no-console
          console.error('Stop STT failed:', error)
        } finally {
          this.isConnected = false
          this.isRecording = false
          this.recognizer = null
        }
      },
      handleRecognitionResult(data) {
        let raw = ''
        if (typeof data === 'string') {
          raw = data
        } else if (data && typeof data === 'object') {
          raw = data.text || data.message || data.content || ''
        }
        this.lastTranscript = this.sanitizeMessage(raw)
      },
      sanitizeMessage(msg) {
        if (msg == null) return ''
        const cleaned = String(msg).replace(/[\u4E00-\u9FFF\u3000-\u303F\uFF00-\uFFEF]/g, '').trim()
        return cleaned
      },
      sendAssistantText() {
        if (!this.assistantText.trim()) return
        // Placeholder for sending text to backend/agent
        // eslint-disable-next-line no-console
        console.log('Assistant text:', this.assistantText)
        this.assistantText = ''
      },
      getTableHeaders() {
        return [
          { text: 'No.', value: 'no', sortable: false, width: '80px' },
          { text: 'Name ※', value: 'name', width: '150px' },
          { text: 'Remarks', value: 'remark', width: '150px' },
          { text: 'Connected Bus ※', value: 'bus', width: '150px' },
          { text: 'Is Valid ※', value: 'valid', width: '100px' },
          { text: 'Generator Type ※', value: 'type', width: '150px' },
          { text: 'Installed Capacity (MW) ※', value: 'installedCapacityMw', width: '180px' },
          { text: 'Maximum Technical Output Rate ※', value: 'maxTechOutputRate', width: '220px' },
          { text: 'Minimum Technical Output Rate ※', value: 'minTechOutputRate', width: '220px' },
          { text: 'Plant Power Consumption Rate', value: 'plantPowerConsumptionRate', width: '200px' },
          { text: 'Maximum Hourly Ramp Rate', value: 'maxHourlyRampRate', width: '180px' },
          { text: 'Allow Start/Stop within Period', value: 'allowStartStopWithinPeriod', width: '200px' },
          { text: 'Minimum On-Time (h)', value: 'minOnTimeH', width: '150px' },
          { text: 'Minimum Off-Time (h)', value: 'minOffTimeH', width: '150px' },
          { text: 'Single Maintenance Duration (days)', value: 'singleMaintenanceDurationDays', width: '220px' },
          { text: 'Maintenance Frequency (times)', value: 'maintenanceFrequencyTimes', width: '200px' },
          { text: 'Initial Operating Status', value: 'initialOperatingStatus', width: '180px' },
          { text: 'Duration of Initial State (h)', value: 'durationOfInitialStateH', width: '180px' },
          { text: 'Time Series Curve', value: 'timeSeriesCurve', width: '150px' },
          { text: 'Voltage Level (kV)', value: 'voltageLevelKv', width: '150px' },
          { text: 'Start/Stop Cost (USD/time) ※', value: 'startStopCostUsdPerTime', width: '180px' },
          { text: 'Initial Cost Constant Term (USD) ※', value: 'initialCostConstantUsd', width: '220px' },
          { text: 'First Segment Cost Coefficient (USD/MWh) ※', value: 'firstSegmentCostUsdPerMWh', width: '280px' },
          { text: 'Output Rate at First Segment Start ※', value: 'firstSegmentStartOutputRate', width: '350px' },
          { text: 'Output Rate at First Segment End ※', value: 'firstSegmentEndOutputRate', width: '350px' },
          { text: 'Second Segment Cost Coefficient (USD/MWh) ※', value: 'secondSegmentCostUsdPerMWh', width: '280px' },
          { text: 'Output Rate at Second Segment End ※', value: 'secondSegmentEndOutputRate', width: '350px' },
          { text: 'Third Segment Cost Coefficient (USD/MWh) ※', value: 'thirdSegmentCostUsdPerMWh', width: '280px' },
          { text: 'Output Rate at Third Segment End ※', value: 'thirdSegmentEndOutputRate', width: '350px' },
          { text: 'Fourth Segment Cost Coefficient (USD/MWh) ※', value: 'fourthSegmentCostUsdPerMWh', width: '280px' },
          { text: 'Output Rate at Fourth Segment End ※', value: 'fourthSegmentEndOutputRate', width: '350px' },
          { text: 'Fifth Segment Cost Coefficient (USD/MWh) ※', value: 'fifthSegmentCostUsdPerMWh', width: '280px' },
          { text: 'Output Rate at Fifth Segment End ※', value: 'fifthSegmentEndOutputRate', width: '350px' },
          { text: 'Total Construction Cost (USD)', value: 'totalConstructionCostUsd', width: '200px' },
          { text: 'Commissioning Date', value: 'commissioningDate', width: '150px' },
          { text: 'Decommissioning Date', value: 'decommissioningDate', width: '150px' }
        ]
      },
  
      generateMockRows() {
        const types = ['Thermal', 'Hydro', 'Wind', 'Solar']
        const statuses = ['On', 'Off']
        const curves = ['Curve A', 'Curve B', 'Curve C']
  
        return Array.from({ length: 8 }, (_, index) => ({
          id: index + 1,
          name: `Generator ${String(index + 1).padStart(2, '0')}`,
          remark: index % 2 === 0 ? 'Peak unit' : 'Base load',
          bus: `Bus-${String(index + 1).padStart(2, '0')}`,
          valid: index % 5 !== 0,
          type: types[index % types.length],
          installedCapacityMw: [500, 300, 150, 100, 600, 450, 200, 80][index],
          maxTechOutputRate: 0.95,
          minTechOutputRate: 0.30,
          plantPowerConsumptionRate: 0.05 + (index % 3) * 0.01,
          maxHourlyRampRate: 0.12 + (index % 4) * 0.02,
          allowStartStopWithinPeriod: index % 3 !== 0,
          minOnTimeH: 2 + (index % 3),
          minOffTimeH: 1 + (index % 2),
          singleMaintenanceDurationDays: 7 + (index % 5),
          maintenanceFrequencyTimes: 2 + (index % 3),
          initialOperatingStatus: statuses[index % statuses.length],
          durationOfInitialStateH: 5 + index,
          timeSeriesCurve: curves[index % curves.length],
          voltageLevelKv: [110, 220, 330][index % 3],
          startStopCostUsdPerTime: 1500 + index * 100,
          initialCostConstantUsd: 50000 + index * 2500,
          firstSegmentCostUsdPerMWh: 20 + index,
          firstSegmentStartOutputRate: 0.30,
          firstSegmentEndOutputRate: 0.50,
          secondSegmentCostUsdPerMWh: 30 + index,
          secondSegmentEndOutputRate: 0.70,
          thirdSegmentCostUsdPerMWh: 40 + index,
          thirdSegmentEndOutputRate: 0.85,
          fourthSegmentCostUsdPerMWh: 50 + index,
          fourthSegmentEndOutputRate: 0.95,
          fifthSegmentCostUsdPerMWh: 60 + index,
          fifthSegmentEndOutputRate: 1.00,
          totalConstructionCostUsd: 2500000 + index * 100000,
          commissioningDate: `202${index % 5}-01-01`,
          decommissioningDate: index % 6 === 0 ? '' : `203${index % 5}-12-31`
        }))
      }
    }
  }
  </script>
  
  <style scoped>
  .table-wrapper {
    overflow-x: auto;
  }
  .page-title {
    white-space: nowrap;
  }
  /* Assistant styles */
  .ai-assistant {
    position: fixed;
    right: 24px;
    bottom: 24px;
    z-index: 1000;
  }
  .ai-dock {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 14px;
    padding: 10px 12px;
    box-shadow: 0 6px 20px rgba(0,0,0,0.12);
  }
  .dock-left {
    font-weight: 600;
    margin-right: 12px;
  }
  .dock-actions { display: flex; align-items: center; }

  .ai-panel {
    width: 360px;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
  }
  .ai-header { padding: 10px 12px; }
  .ai-body { padding: 14px; }
  .ai-greeting { color: #5f6368; margin-bottom: 12px; }
  .mic-btn { width: 84px; height: 84px; }
  </style>
  
  
  
  